package com.hmdp.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author wzh
 * @create 2022/6/14 20:53
 * @Description： 实使用redis来实现分布式锁
 */
public class SimpleRedisLock implements ILock {

    private StringRedisTemplate stringRedisTemplate;

    private String name; //业务名称
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    private static final String KEY_PREFIX = "lock:";  //前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString() + "-";//用于区分不同的jvm
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public boolean tryLock(long timeOutSec) {
        //        获取线程唯一标识
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeOutSec, TimeUnit.SECONDS);
//       aBoolean为包装类，返回值为基本类型，所以此处有一个自动拆箱的过程，有自动拆箱则存在安全的风险
        return Boolean.TRUE.equals(aBoolean);// aBoolean为true在返回true,aBoolean为false或者null则返回false，避免空指针的风险
    }
    @Override
    public void unLock() {
                  //调用lua脚本  防止之前的方法在判断完之后，在释放锁之前发生阻塞而发生误删的情况，使用lua脚本可以满足原子性
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                                    Collections.singletonList(KEY_PREFIX + name),//得到一个单例线程
                ID_PREFIX + Thread.currentThread().getId());


    }

//    @Override
//    public void unLock() {
////        获取线程标识
//        String threadId = ID_PREFIX + Thread.currentThread().getId();
////        获取锁中的标识
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
////        判断是否一致
//        if (threadId.equals(id)) {
////            释放锁
//            stringRedisTemplate.delete(KEY_PREFIX + name);
//
//        }
//
//    }
}
